<?php

namespace App\Admin\Metrics\Examples;

use App\Models\Order;
use Dcat\Admin\Admin;
use Dcat\Admin\Widgets\Metrics\Card;
use Illuminate\Contracts\Support\Renderable;
use Illuminate\Http\Request;

class TotalHandlingFeeCard extends Card
{
    /**
     * 卡片底部内容.
     *
     * @var string|Renderable|\Closure
     */
    protected $footer;

    protected $page;
    protected $perPage;


    public function __construct($page = 1, $perPage = 20)
    {
        $this->page = $page;
        $this->perPage = $perPage;
        parent::__construct();
    }

    /**
     * 初始化卡片.
     */
    protected function init()
    {
        parent::init();

        $this->title('发布手续费总金额');
    }

    /**
     * 处理请求.
     *
     * @param Request $request
     *
     * @return void
     */
    public function handle(Request $request)
    {
        $orderNumber = $request->get('order_number');
        $type = $request->get('type');
        $status = $request->get('status');
        $schoolId = $request->get('school_id');
        $page = $request->get('page');
        $perPage = $request->get('perPage');
        $where = [];
        if (Admin::user()->school_id) {
            $where['school_id'] = Admin::user()->school_id;
        } else {
            if ($schoolId) {
                $where['school_id'] = $schoolId;
            }
        }
        if ($orderNumber) {
            $where['order_number'] = $orderNumber;
        }
        if ($type) {
            $where['type'] = $type;
        }
        if ($status) {
            $where['status'] = $status;
        }
        $totalAmount = Order::where($where)->where('status', '!=', 1)->orderBy('id', 'desc')->get()->sum('handling_fee');
        $this->content($totalAmount);
    }


    // 传递自定义参数到 handle 方法
    public function parameters(): array
    {
        return [
            'school_id' => request()->input('school_id'),
            'order_number' => request()->input('order_number'),
            'type' => request()->input('type'),
            'status' => request()->input('status'),
            'page' => $this->page,
            'perPage' => $this->perPage,
        ];
    }


    /**
     * 设置卡片底部内容.
     *
     * @param string|Renderable|\Closure $footer
     *
     * @return $this
     */
    public function footer($footer)
    {
        $this->footer = $footer;

        return $this;
    }

    /**
     * 渲染卡片内容.
     *
     * @return string
     */
    public function renderContent()
    {
        $content = parent::renderContent();

        return <<<HTML
<div class="d-flex justify-content-between align-items-center mt-1" style="margin-bottom: 2px">
    <h2 class="ml-1 font-lg-1">{$content}</h2>
</div>
<div class="ml-1 mt-1 font-weight-bold text-80">
    {$this->renderFooter()}
</div>
HTML;
    }

    /**
     * 渲染卡片底部内容.
     *
     * @return string
     */
    public function renderFooter()
    {
        return $this->toString($this->footer);
    }
}
